<template>
  <div>
    <el-dialog :title="isEdit?'修改验收入库':'验收入库'"
               :visible.sync="dialogForm"
               width="1200px">
      <el-form :inline="true"
               ref="form"
               :model="form"
               class="add-form"
               label-width="110px">
        <h3>验收信息</h3>
        <hr />
        <el-row>
          <el-col :span="8"
                  class="el-height"><span class="labels">验收单号:</span>{{form.checkAcceptNo}}</el-col>
          <el-col :span="8"
                  class="el-height"><span class="labels">车船号:</span>{{form.transhipNo}}</el-col>
          <el-col :span="8"
                  class="el-height"><span class="labels">货主:</span>{{form.cargoOwnerName}}</el-col>
          <el-col :span="8"
                  class="el-height"><span class="labels">入库方式:</span>{{form.inWayName}}</el-col>
          <el-col :span="8"
                  class="el-height"><span class="labels">运输方式:</span>{{form.transportWay | _filterTransportModeType}}</el-col>
        </el-row>
        <h3>物资信息</h3>
        <hr />
        <el-row>
          <el-col :span="12">
            <el-form-item label="品名"
                          prop="cargoName">
              <el-select v-model="form.cargoName"
                         placeholder="请选择"
                         clearable
                         filterable
                         @change="handleCargoChange('normOneDisabled')">
                <el-option v-for="(item,index) in cargoNameList"
                           :key="index"
                           :label="item.cargoName"
                           :value="item.cargoName"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="规格"
                          required>
              <el-col :span="8">
                <auto-search-dic style="width: 100px;"
                                 @selectName="v=>form.normOne=v"
                                 :name="form.normOne"
                                 code="CARGO_GGY"></auto-search-dic>
              </el-col>
              <el-col :span="8">
                <auto-search-dic style="width: 100px;"
                                 @selectName="v=>form.normTwo=v"
                                 :name="form.normTwo"
                                 code="CARGO_GGE"></auto-search-dic>
              </el-col>
              <el-col :span="8">
                <auto-search-dic style="width: 100px;"
                                 @selectName="v=>form.normThree=v"
                                 :name="form.normThree"
                                 code="CARGO_GGS"></auto-search-dic>
              </el-col>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="材质"
                          prop="material">
              <auto-search-dic v-model="form.material"
                               @selectName="v=>form.material=v"
                               :name="form.material"
                               code="CARGO_CZ"></auto-search-dic>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="生产厂家"
                          prop="madeBy">
              <auto-search-dic v-model="form.madeBy"
                               @selectName="v=>form.madeBy=v"
                               :name="form.madeBy"
                               code="CARGO_SCZ"></auto-search-dic>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="管理方式"
                          prop="manageWay">
              <el-select v-model="form.manageWay"
                         placeholder="请选择"
                         clearable>
                <el-option v-for="[key, val] in _dictManagement"
                           :key="key"
                           :label="val"
                           :value="key"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="计量方式"
                          prop="measureWay">
              <el-select v-model="form.measureWay"
                         placeholder="请选择"
                         clearable>
                <el-option v-for="[key, val] in _dictMeterStyle"
                           :key="key"
                           :label="val"
                           :value="key"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属仓库"
                          prop="warehouseCode">
              <el-select v-model="form.warehouseCode"
                         placeholder="请选择"
                         clearable>
                <el-option v-for="(item,index) in warehouseList"
                           :key="index"
                           :label="item.name"
                           :value="item.code"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="验收重量(吨)"
                          prop="checkAcceptWeight">
              <el-input type="text"
                        placeholder="请输入内容"
                        :maxLength="$maxLength"
                        v-model="form.checkAcceptWeight"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="验收件数"
                          prop="checkAcceptNum">
              <el-input type="text"
                        placeholder="请输入内容"
                        :maxLength="$maxLength"
                        v-model="form.checkAcceptNum"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="验收数量"
                          prop="checkAcceptCount">
              <el-input type="text"
                        placeholder="请输入内容"
                        :maxLength="$maxLength"
                        v-model="form.checkAcceptCount"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <h3>验收明细</h3>
        <hr />
        <el-row class="button">
          <el-button @click="addList">添加清单</el-button>
          <!-- <el-button @click="handleRemoveAll">删除</el-button> -->
          <el-button @click="fillCargoLocation">填写货位</el-button>
          <el-button @click="addInfo">附件信息</el-button>
        </el-row>
        <el-table :data="form.detailVoList"
                  border
                  stripe
                  @selection-change="handleSelectionChange"
                  max-height="550">
          <el-table-column type="selection"
                           width="50"></el-table-column>
          <el-table-column label="序号"
                           type="index"
                           width="50"></el-table-column>
          <el-table-column prop="trackingNo"
                           label="跟踪号"
                           width="100">
            <template slot-scope="scope">
              <el-input v-model="scope.row.trackingNo"
                        disabled></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="ifSmall"
                           label="是否小件"
                           width="100">
            <template slot-scope="scope">
              <el-select v-model="scope.row.ifSmall"
                         placeholder="请选择"
                         clearable>
                <el-option v-for="[key, val] in _dictTrueOrFalse"
                           :key="key"
                           :label="val"
                           :value="key"></el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="lbsTimes"
                           label="磅次"
                           width="80">
            <template slot-scope="scope">
              <el-input v-model="scope.row.lbsTimes"
                        disabled></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="lbsWeight"
                           label="合磅重量"
                           width="80">
            <template slot-scope="scope">
              <el-input v-model="scope.row.lbsWeight"
                        disabled></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="checkAcceptWeight"
                           label="验收重量"
                           width="100">
            <template slot-scope="scope">
              <el-input v-model="scope.row.checkAcceptWeight"
                        disabled></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="checkAcceptCount"
                           label="数量"
                           width="80">
            <template slot-scope="scope">
              <el-input v-model="scope.row.checkAcceptCount"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="tagWeight"
                           label="标牌重量"
                           width="100">
            <template slot-scope="scope">
              <el-input v-model.number="scope.row.tagWeight"
                        :disabled="form.measureWay==='RULER'"
                        @blur="getCheckData(scope.row.lbsWeight)"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="rulerWeight"
                           label="检尺重量"
                           width="100">
            <template slot-scope="scope">
              <el-input v-model.number="scope.row.rulerWeight"
                        :disabled="form.measureWay!=='RULER'"
                        @blur="getCheckData"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="netWeight"
                           label="净重"
                           width="100">
            <template slot-scope="scope">
              <el-input v-model="scope.row.netWeight"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="grossWeight"
                           label="毛重"
                           width="100">
            <template slot-scope="scope">
              <el-input v-model="scope.row.grossWeight"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="roomCode"
                           label="库房"
                           min-width="100">
            <template slot-scope="scope">
              <el-select v-model="scope.row.roomCode"
                         placeholder=""
                         :disabled="disabled"
                         clearable>
                <!-- <el-option v-for="[key, val] in _dictLimitFactor"
                           :key="key"
                           :label="val"
                           :value="key"></el-option> -->
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="spanNo"
                           label="跨数"
                           min-width="100">
            <template slot-scope="scope">
              <el-select v-model="scope.row.spanNo"
                         placeholder=""
                         :disabled="disabled"
                         clearable>
                <!-- <el-option v-for="[key, val] in _dictLimitFactor"
                           :key="key"
                           :label="val"
                           :value="key"></el-option> -->
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="aulaNo"
                           label="间数"
                           min-width="100">
            <template slot-scope="scope">
              <el-select v-model="scope.row.aulaNo"
                         placeholder=""
                         :disabled="disabled"
                         clearable>
                <!-- <el-option v-for="[key, val] in _dictLimitFactor"
                           :key="key"
                           :label="val"
                           :value="key"></el-option> -->
              </el-select>
            </template>
          </el-table-column>
          <el-table-column prop="rowNo"
                           label="排数"
                           width="100">
            <template slot-scope="scope">
              <el-input v-model="scope.row.rowNo"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="stackNo"
                           label="垛数"
                           width="100">
            <template slot-scope="scope">
              <el-input v-model="scope.row.stackNo"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="tierNo"
                           label="层高"
                           width="100">
            <template slot-scope="scope">
              <el-input v-model="scope.row.tierNo"></el-input>
            </template>
          </el-table-column>

          <el-table-column prop="baleNo"
                           label="捆包号"
                           width="100">
            <template slot-scope="scope">
              <el-input v-model="scope.row.baleNo"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="stoveNo"
                           label="炉批号"
                           width="100">
            <template slot-scope="scope">
              <el-input v-model="scope.row.stoveNo"></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="carNo"
                           label="车牌号"
                           width="100">
            <template slot-scope="scope">
              <el-input v-model="scope.row.carNo"
                        disabled></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="jobPointName"
                           label="作业点"
                           width="100">
            <template slot-scope="scope">
              <el-input v-model="scope.row.jobPointName"
                        disabled></el-input>
            </template>
          </el-table-column>
          <el-table-column prop="acceptAttachments"
                           label="验收附件信息"
                           width="150">
            <template slot-scope="scope">
              <download v-model="scope.row.acceptAttachments"></download>
            </template>
          </el-table-column>
          <el-table-column prop="remark"
                           label="验收备注"
                           width="100">
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark"></el-input>
            </template>
          </el-table-column>
          <el-table-column label="操作"
                           align="center"
                           min-width="60"
                           fixed="right">
            <template slot-scope="scope">
              <!-- <el-button type="text"
                         size="small"
                         @click="handleDialogForm(scope.row)">添加</el-button> -->
              <el-button type="text"
                         size="small"
                         @click="handleRemove(scope.row,scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div slot="footer"
           class="dialog-footer">
        <el-button type="primary"
                   @click="handleSave">保 存</el-button>
        <el-button type="primary"
                   @click="handleSubmit">提 交</el-button>
        <el-button @click="dialogForm = false">返 回</el-button>
      </div>
    </el-dialog>
    <!-- 磅重信息 -->
    <add-list-form ref="addListForm"
                   @load="addData"></add-list-form>
    <!-- 货位信息 -->
    <cargo-location-info ref="cargoLocationInfo"
                         @load="getLocation"></cargo-location-info>
    <!-- 附加信息 -->
    <updown-dialog-form ref="updownDialogForm"
                        @load="getUrl"></updown-dialog-form>
  </div>
</template>

<script>
import {
  addAcceptance,
  updateAcceptanceIn,
  getDetailList
} from '@/api/enter/acceptanceIn'
import { getCargoNameList } from '@/api/things/accountPageList'
import { getWarehouseList } from '@/api/adminWarehouse/adminWarehouse' //所属仓库来源于仓库设置
import autoSearchDic from '@/components/autocomplete/autoSearchDic'
import addListForm from './addListForm'
import cargoLocationInfo from './cargoLocationInfo'
import updownDialogForm from './updownDialogForm'
import download from '@/components/download'

export default {
  name: 'checkInForm',
  components: {
    autoSearchDic,
    addListForm,
    cargoLocationInfo,
    updownDialogForm,
    download
  },
  data() {
    return {
      form: this.clearForm(),
      dialogForm: false,
      disabled: true,
      isEdit: false,
      data: [],
      cargoNameList: [], //货名列表
      warehouseList: [],
      multipleSelection: [],
      lbsWeight: null //合磅重量
    }
  },
  mounted() {
    //获取仓库
    getWarehouseList().then(res => {
      this.warehouseList = res.data.aaData
    })
    //获取货名
    getCargoNameList(this.$store.state.user.currentUser.org.id).then(res => {
      this.cargoNameList = res.data.aaData
    })
  },
  watch: {
    data: 'addData',
    data: 'getCheckData'
  },
  methods: {
    clearForm() {
      return {}
    },
    //添加清单
    addList() {
      this.$refs.addListForm.disabled = false
      this.$refs.addListForm.dialogForm = true
    },
    //多选
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    //填写货位
    fillCargoLocation() {
      if (this.multipleSelection.length === 0) {
        this.$message({ type: 'error', message: '请至少选择一条数据' })
      } else {
        let data = this.multipleSelection
        //给货位信息弹框赋值
        this.$refs.cargoLocationInfo.form = {
          roomName: data[0].roomName,
          spanNo: data[0].spanNo,
          aulaNo: data[0].aulaNo
        }
        this.$refs.cargoLocationInfo.dialogForm = true
      }
    },
    //附件信息
    addInfo() {
      if (this.multipleSelection.length === 0) {
        this.$message({ type: 'error', message: '请至少选择一条数据' })
      } else {
        this.$refs.updownDialogForm.dialogForm = true
      }
    },
    //获取附件信息
    getUrl(val) {
      this.multipleSelection.forEach(element => {
        element.remark = val.remark
        element.acceptAttachments = val.attachments
      })
    },
    //获取货物信息
    getLocation(val) {
      this.multipleSelection.forEach(element => {
        element.rowNo = val.rowNo
        element.stackNo = val.stackNo
        element.tierNo = val.tierNo
      })
    },
    //添加清单
    addData(val) {
      let aa = {
        aulaNo: '01', //间
        baleNo: null, //捆包号
        carNo: this.form.carNo, //车牌号
        checkAcceptCount: null, //数量
        checkAcceptWeight: null, //验收重量
        remark: '', //备注
        acceptAttachments: null, //附件信息
        detailAttachments: null,
        grossWeight: null, //毛重
        ifSmall: false, //是否小件
        jobPointCode: this.form.jobPointCode,
        jobPointName: this.form.jobPointName, //作业点
        lbsTimes: val.lbsTimes, //磅次
        lbsWeight: val.lbsWeight, //合磅重量
        netWeight: null, //净重
        roomCode: 'A01', //库房
        roomName: 'A01', //库房
        rowNo: '', //排数
        rulerWeight: null, //检尺重量
        spanNo: '01', //跨数
        stackNo: '', //垛数
        stoveNo: null, //炉批号
        tagWeight: null, //标牌重量
        tierNo: '', //层高
        trackingNo: val.trackingNo, //跟踪号
        transhipNo: null //车船号
      }
      if (val.length === 0) {
        this.form.detailVoList = [] //清除事件监听新增的无效数据
      } else {
        this.form.detailVoList.push(aa)
        //计量方式为检斤
        if (this.form.measureWay === 'WEIGHT') {
          let count = 0
          let checkAcceptWeight = 0
          this.form.detailVoList.forEach(element => {
            if (element.lbsTimes === val.lbsTimes) {
              count++
              checkAcceptWeight = element.lbsWeight / count //计算验收重量
            }
          })
          //回填计算后的验收重量
          this.form.detailVoList.forEach(item => {
            if (item.lbsTimes === val.lbsTimes) {
              item.checkAcceptWeight = checkAcceptWeight
            }
          })
        }
      }
    },
    //回填验收重量
    getCheckData() {
      if (this.form.measureWay === 'RULER') {
        //计量方式为检尺
        this.form.detailVoList.forEach(item => {
          item.checkAcceptWeight = item.rulerWeight
        })
      } else if (this.form.measureWay === 'ID') {
        //计量方式为标识
        this.form.detailVoList.forEach(item => {
          item.checkAcceptWeight = item.tagWeight
        })
      } else if (this.form.measureWay === 'WEIGHT') {
        //计量方式为检斤
        let detailVoList = this.form.detailVoList
        let temp = detailVoList[0].lbsTimes
        let count = 0
        let map = []
        //计算每个磅次的数量
        for (let i = 0; i < detailVoList.length; i++) {
          if (detailVoList[i].lbsTimes === temp) {
            count++
          } else {
            //记录当前结果
            map.push({ lbsTimes: temp, count: count })
            temp = detailVoList[i].lbsTimes
            count = 1
          }
        }
        //记录最后一个结果
        map.push({ lbsTimes: temp, count: count })
        console.log(JSON.stringify(map))

        let surplus = detailVoList[0].lbsWeight //剩余重量=合磅重量-每次录入的标牌重量
        for (let i = 0; i < map.length; i++) {
          for (let j = 0; j < detailVoList.length; j++) {
            if (detailVoList[j].lbsTimes === map[i].lbsTimes) {
              if (
                detailVoList[j].tagWeight &&
                surplus > detailVoList[j].tagWeight
              ) {
                //如果录入的标牌重量小于剩余重量，验收重量等于标牌重量
                detailVoList[j].checkAcceptWeight = detailVoList[j].tagWeight
                surplus = surplus - detailVoList[j].tagWeight
                console.log('剩余', surplus)
              } else if (
                detailVoList[j].tagWeight &&
                surplus <= detailVoList[j].tagWeight
              ) {
                console.log('剩余2', surplus)
                console.log('count', map[i].count)

                //如果录入的标牌重量大于剩余重量，验收重量等于剩余重量除以剩余未录入标牌重量的行数
                let list = []
                list.push(detailVoList[j])
                //列出没有录入标牌重量的行
                detailVoList.forEach(element => {
                  if (element.lbsTimes === map[i].lbsTimes) {
                    if (!element.tagWeight) {
                      list.push(element)
                    }
                  }
                })
                list.forEach(element => {
                  element.checkAcceptWeight = surplus / (map[i].count - j)
                })
              }
            } else {
              console.log('ee')
              surplus = detailVoList[j].lbsWeight

              i++
              console.log('surplus22', surplus)
              console.log('i', i)
            }
          }
        }
      }
    },
    //删除
    handleRemove(val, index) {
      this.form.detailVoList.splice(index, 1)
      let count = 0
      let checkAcceptWeight = 0
      this.form.detailVoList.forEach(element => {
        if (element.lbsTimes === val.lbsTimes) {
          count++
          checkAcceptWeight = element.lbsWeight / count //计算验收重量
        }
      })
      //回填计算后的验收重量
      this.form.detailVoList.forEach(item => {
        if (item.lbsTimes === val.lbsTimes) {
          item.checkAcceptWeight = checkAcceptWeight
        }
      })
    },
    //保存
    handleSave() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.isEdit ? this.handleSaveEdit() : this.handleSaveAdd()
        } else {
          this.$message({
            message: '请检查表单',
            type: 'error'
          })
        }
      })
    },
    //保存：修改验收入库
    handleSaveEdit() {
      this.form.type = 1
      updateAcceptanceIn(this.form.id, this.form).then(res => {
        this.$message({ message: '编辑成功!', type: 'success' })
        this.dialogForm = false
        this.$emit('load')
      })
    },
    //保存：验收入库
    handleSaveAdd() {
      this.form.type = 1
      addAcceptance(this.form.id, this.form).then(res => {
        this.$message({ message: '保存成功!', type: 'success' })
        this.dialogForm = false
        this.$emit('load')
      })
    },
    //提交
    handleSubmit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          this.isEdit ? this.handleSubmitEdit() : this.handleSubmitAdd()
        } else {
          this.$message({
            message: '请检查表单',
            type: 'error'
          })
        }
      })
    },
    //提交：修改验收入库
    handleSubmitEdit() {
      this.form.type = 2
      updateAcceptanceIn(this.form.id, this.form).then(res => {
        this.$message({ message: '提交成功!', type: 'success' })
        this.dialogForm = false
        this.$emit('load')
      })
    },
    //提交：验收入库
    handleSubmitAdd() {
      this.form.type = 2
      addAcceptance(this.form.id, this.form).then(res => {
        this.$message({ message: '提交成功!', type: 'success' })
        this.dialogForm = false
        this.$emit('load')
      })
    }
  }
  // computed:{
  //   weight:function() {
  //     return this.lbsWeight/3
  //   }
  // }
}
</script>

<style rel="stylesheet/scss" lang="scss" scoped>
.el-height {
  margin: 10px 0;
}
h3 {
  margin: 10px 0;
}
.labels {
  margin-right: 5px;
}
.button {
  margin-top: 10px;
  margin-bottom: 10px;
}
</style>
